package com.demo.agent.firstagent.javassist;

import javassist.*;

import java.lang.reflect.Method;


/**
 * @author 许路路
 */
public class OneDemo {

    public static void main(String[] args) throws Exception {
        //1.获得类池
        ClassPool pool = ClassPool.getDefault();
        //2.创建类
        CtClass ctClass = pool.makeClass("com.demo.agent.firstagent.javassist.demo");
        //3.创建属性
        CtField name = CtField.make("private String name;", ctClass);//属性定义 对象
        CtField age = CtField.make("private int age;", ctClass);
        //4.添加属性
        ctClass.addField(name);
        ctClass.addField(age);
        //5.创建方法
        CtMethod make = CtMethod.make("public String getName() {return name;}", ctClass);
        CtMethod make1 = CtMethod.make("public void setName(String name) {this.name = name;}", ctClass);
        //6.添加方法
        ctClass.addMethod(make);
        ctClass.addMethod(make1);
        //7.添加构造器
        CtConstructor ctConstructor = new CtConstructor(new CtClass[]{}, ctClass);//无参数构造器
        ctConstructor.setBody("{}");
        CtConstructor ctConstructor1 = new CtConstructor(new CtClass[]{CtClass.intType, pool.get("java.lang.String")}, ctClass);//指定参数构造器
        ctConstructor1.setBody("{this.name=$2;this.age=$1;}");//$1代表第一个参数，$2代表第二个参数，$0代表this
        //8.添加构造器
        ctClass.addConstructor(ctConstructor);
        ctClass.addConstructor(ctConstructor1);
        //ctClass.writeFile();
        Class<?> clazz = pool.toClass(ctClass);
        //Method[] methods = clazz.getMethods();
        Method method01 = clazz.getDeclaredMethod("setName", String.class);
        Object obj = clazz.newInstance();
        method01.invoke(obj, "许路路");
        Method method02 = clazz.getDeclaredMethod("getName");
        Object object = method02.invoke(obj);
        System.out.println("................" + object);

    }

}
